<?php
namespace app\store\model;
use app\common\model\CategoryServe as CategoryServeModel;

/**
 * 小程序服务类目模型
 */
class CategoryServe extends CategoryServeModel
{
	/**
     * 添加
     */
    public function add($data,$category)
    {
		$id = explode('.',$data['id']);
		$category = $category[$id[0]]['children'][$id[1]];
		$media_id = '';
		$data['ca_name'] = '';
		if($category['sensitive_type']==1){
			if (!isset($data['certicates']) || empty($data['certicates'])) {
				$this->error = '请上传资质图片';
				return false;
			}
			$data['ca_name'] = $category['qualify']['exter_list'][0]['inner_list'][0]['name'];
			$media_id = up_temp_material($data['certicates']); //上传临时素材
		}
		$data['first'] = $category['father'];
		$data['first_name'] = $category['father_name'];
		$data['second'] = $category['id'];
		$data['second_name'] = $category['name'];
		$data['wxapp_id'] = self::$wxapp_id;
		//提交到微信端
		$access_token = getAccessToken();
		$url = 'https://api.weixin.qq.com/cgi-bin/wxopen/addcategory?access_token='.$access_token;
		$post = [
			'categories' => [
				[
					'first' => $data['first'],
					'second' => $data['second'],
					'certicates' => [
						'key' => $data['ca_name'],
						'value' => $media_id
					]
				]
			]
		];
		$result = json_decode(http_post($url,$post),true);
		if($result['errcode']!=0){
			$this->error = wx_err_msg($result['errcode']);
			return false;
		}
        return $this->allowField(true)->save($data);
    }

    /**
     * 删除
     */
    public function remove()
    {
		$access_token = getAccessToken();
		$url = 'https://api.weixin.qq.com/cgi-bin/wxopen/deletecategory?access_token='.$access_token;
		$data = [
			'first' => $this['first'],
			'second' => $this['second']
		];
		$result = json_decode(http_post($url,$data),true);
		if($result['errcode']!=0){
			$this->error = wx_err_msg($result['errcode']);
			return false;
		}
        return $this->delete();
    }
}
